// pages/login/login.js
const global = getApp().globalData
import {
  authToken,
  init
} from '../../utils/api.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    account: wx.getStorageSync('account') || '',
    iamAccount: wx.getStorageSync('iamAccount') || '',
    iamPassword: wx.getStorageSync('iamPassword') || '',
  },
  onAuth: function () {
    console.log(this.data)
    authToken({
      account: this.data.account,
      iamAccount: this.data.iamAccount,
      iamPassword: this.data.iamPassword
    }).then(res => {
      console.log('onAuth res', res)
      wx.clearStorageSync()
      if (res.token && res.token.project) {
        global.project_id = res.token.project.id
        wx.setStorageSync('project_id', res.token.project.id)
        wx.setStorageSync('account', this.data.account)
        wx.setStorageSync('iamAccount', this.data.iamAccount)
        wx.setStorageSync('iamPassword', this.data.iamPassword)
        console.log('onAuth res2=', global.region, res.token.project.name, res.token.project.id);
        //检查资源产品
        let params ={ 'project_id': global.project_id }
        init(params, res => {
          global.products = res;
          wx.navigateTo({
            url: '../home/index',
          })
        })
      } else {
        wx.showModal({
          title: res.error_code || res.error.title,
          content: res.error_msg || res.error.message,
          showCancel: false,
          success(res) {}
        })
      }
    }, err => {
      console.log('onAuth err', err)
      wx.showModal({
        title: '提示',
        content: '账号或密码错误',
        showCancel: false,
        success(res) {}
      })
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
this.onAuth();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})